package com.sinodata.bsm.cicp.collector.common;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.collector.mysql.MySQLUtil;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 *
 * <p>
 * Description: 简单SQL采集器，每条查询记录作为一个采集结果。
 * </p>
 */
public class SingleSqlCollector extends AbstractJDBCCollector {

    private static final Logger logger = Logger.getLogger(SingleSqlCollector.class);

    public SingleSqlCollector() {
    }

    /**
     * Modify by chao.liu 修改如下 <br/>
     * 1.将查询结果集抽出为私有方法.[抽出的方法名为:getResPropertyValueXList] <br/>
     * 2.判断Mysql版本为4的时候不查询,直接返回所有值为N/A的结果集
     */
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String dbtype = this.paramMap.get("DBType");
        String dbname = this.paramMap.get("DBName");
        String sql = this.paramMap.get("SQL");
        String iip = this.paramMap.get("DBIP");
        String[] propMetas = getPropMeta();
        if (iip != null && !"".equals(iip)) {
            ip = iip;
        }
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        if (MySQLUtil.isVersion4(dbtype, ip, dbname)) {
            MySQLUtil.getResPropertyValueXList(propMetas, values);
        } else {
            getResPropertyValueXList(ip, dbtype, dbname, sql, propMetas, values);
        }
        return values;
    }

    private void getResPropertyValueXList(String ip, String dbtype, String dbname, String sql, String[] propMetas, List<ResPropertyValue> values) throws CollectorException {
        try {
            ResultSet rs = this.getCachedResultSet(dbtype, ip, dbname, sql);
            ResultSetMetaData md = rs.getMetaData();
            if (md.getColumnCount() == propMetas.length) {
                while (rs.next()) {
                    ResPropertyValue propertyValueX = new ResPropertyValue();
                    ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
                    for (int i = 0; i < propValues.length; i++) {
                        String v = rs.getObject(i + 1).toString();
                        String[] vArray = v.split("\\.");
                        String vs = "";
                        int count = 0;
                        if (vArray.length > 1) {
                            Pattern p = Pattern.compile("0");
                            Matcher m = p.matcher(vArray[1]);
                            while (m.find()) {
                                count++;
                            }
                            if (count < vArray[1].length()) {
                                vs = decimal(v);
                            } else {
                                vs = vArray[0];
                            }
                        } else {
                            vs = v;
                        }
                        propValues[i] = ResPropertyValue.createPropValue(vs, propMetas[i]);
                    }
                    propertyValueX.setValues(propValues);
                    values.add(propertyValueX);
                    //如果查询出多条，也只显示一条记录的相关字段，之后跳出返回结果
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("failed to collect by SingleSqlCollector", e);
            throw new CollectorException(e);
        }
    }

    private String decimal(String v) {
        boolean rest = true;
        String vs = "";
        try {
            vs = Math.round((Double.parseDouble(v)) * 100) / 100.00 + "";
        } catch (NumberFormatException e) {
            rest = false;
        }
        if (rest) {
            return vs;
        } else {
            return v;
        }
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "DBType", "DBName", "SQL", "FieldNum", "DBIP" };
    }

    @Override
    public String[] getPropMeta() {
        int count = Integer.parseInt(this.paramMap.get("FieldNum"));
        String[] propMetas = new String[count];
        for (int i = 1; i <= propMetas.length; i++) {
            propMetas[i - 1] = "$" + i;
        }
        return propMetas;
    }
}
